package com.xnyzc.lhy.nio.netty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.constant.MethodConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.penum.nio.EMileageBilling;
import com.xnyzc.lhy.common.penum.nio.ENettyGps;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.nio.entity.netty.DriverVehInfo;
import com.xnyzc.lhy.nio.feign.netty.FeignNettyService;
import com.xnyzc.lhy.nio.mongo.TrackInfo;
import com.xnyzc.lhy.nio.mq.MQProducer;
import com.xnyzc.lhy.order.entity.gps.OaDVehicleGps;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * Netty common
 *
 * @author liuju
 * @create 2019-07-17 13:23
 */
@Component
@Slf4j
public class NettyCommon {

    @Autowired
    private RedisCommon redisCommon;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private NettyPushCommon pushCommon;

    @Autowired
    private FeignNettyService feignNettyService;

    @Autowired
    private MQProducer producer;

    public static String serviceId;

    @Value("${global.amap.lyServiceId}")
    public void setServiceId(String amapServiceId) {
        serviceId = amapServiceId;
    }


    /**
     * 添加实时轨迹
     *
     * @param ctx     客户端
     * @param jsonCon 定位数据
     */
    public void genDriverUploadLocHandle(ChannelHandlerContext ctx, JSONObject jsonCon, String method) {
        //判断Con中数据是否为空并且格式正确
        String redisKey = jsonCon.getString(ENettyGps.key.getValue());
        String orderNo = jsonCon.getString(ENettyGps.orderNo.getValue());
        //[{orderNo=YNC60965DB700154C6941_363, lng=104.06682186030073, cityId=510100, speed=0,
        // key=gps:oa_d_vehicle_gps:2476668218441728, lat=30.629001675759515}]
        log.info("ORDER_HISTORY 订单号:[{}],上传key:[{}] GPS_LOCATION 上传信息:[{}]", orderNo, redisKey, jsonCon);
        //根据前缀截取获取ID
        String[] split = redisKey.split(RedisPrefixConstant.GPS_VEH_KEY_PREFIX);
        if (split.length < 1) {
            NettyMsg.setErrMsg(method, MessageConstant.REDIS_KEY_ERROR);
            return;
        }
        Date date = new Date();
        //获取ID查询出信息
        String vehicleId = split[1];
        OaDVehicleGps oaDVehicleGps = null;
        String gpsJson = redisCommon.getStr(redisKey);
        TrackInfo trackInfo = new TrackInfo();
        if (!CheckUtil.strIsEmpty(gpsJson)) {
            oaDVehicleGps = JSON.parseObject(gpsJson, OaDVehicleGps.class);
        } else {
            DriverVehInfo vehInfo = feignNettyService.getDDriverVehicleInfo(vehicleId);
            oaDVehicleGps = new OaDVehicleGps();
            oaDVehicleGps.setGpsId(IDUtil.nextId());
            oaDVehicleGps.setCreateTime(date);
            //默认经济型
            oaDVehicleGps.setVehType(0);
            if (CheckUtil.objIsEmpty(vehInfo)) {
                return;
            }
            oaDVehicleGps.setVehId(Long.valueOf(vehInfo.getVehId()));
            oaDVehicleGps.setDriverId(vehInfo.getDriverId());
            oaDVehicleGps.setCreateUser(vehInfo.getDriverId());
            oaDVehicleGps.setVehType(vehInfo.getVehType());
            trackInfo.setDriverId(vehInfo.getDriverId());
        }
        //数据回填
        oaDVehicleGps.setOrderNo(orderNo);
        oaDVehicleGps.setLng(jsonCon.getString(ENettyGps.lng.getValue()));
        oaDVehicleGps.setLat(jsonCon.getString(ENettyGps.lat.getValue()));
        oaDVehicleGps.setSpeed(jsonCon.getString(ENettyGps.speed.getValue()));
        oaDVehicleGps.setUpdateTime(date);
        trackInfo.setDriverId(Long.parseLong(vehicleId));
        String jsonGps = JSON.toJSONString(oaDVehicleGps);
        redisCommon.set(redisKey, jsonGps);
//        redisCommon.expire(redisKey, 60 * 5);

        log.info("ORDER_HISTORY 订单号:[{}],上传key:[{}] GPS_LOCATION 保存到redis中的数据:[{}]", orderNo, redisKey, jsonGps);
        //保存mongo

        Long locatedTime=System.currentTimeMillis();
        String lng = jsonCon.getString(ENettyGps.lng.getValue());
        String lat = jsonCon.getString(ENettyGps.lat.getValue());
        String lngTmp=lng.substring(lng.indexOf(".")+1);
        if (lngTmp.length()>6){
            lng=lng.substring(0,lng.indexOf(".")+7);
        }
        String latTmp=lat.substring(lat.indexOf(".")+1);
        if (latTmp.length()>6){
            lat=lat.substring(0,lat.indexOf(".")+7);
        }
        if (CheckUtil.strIsEmpty(orderNo)) {
            orderNo="-1";
        }
        Double speed= Double.parseDouble(jsonCon.getString(ENettyGps.speed.getValue()));
        trackInfo.setOrderNo(orderNo);
        trackInfo.setId(IDUtil.nextId());
        trackInfo.setLat(lat);
        trackInfo.setLng(lng);
        trackInfo.setSpeed(speed);
        trackInfo.setServiceId(Long.parseLong(serviceId));
        trackInfo.setOperateTime(LocalDateTime.now());
        mongoTemplate.save(trackInfo);
        if (CheckUtil.strIsEmpty(orderNo)) {
            log.info("ORDER_HISTORY 订单号:[{}],上传key:[{}] GPS_LOCATION 当前订单上传订单为空", orderNo, redisKey);
            NettyServerService.sendMsgToClient(ctx, NettyMsg.setJsonMsg(MethodConstant.PING, "{}"));
            return;
        }
        NettyServerService.sendMsgToClient(ctx, NettyMsg.setJsonMsg(MethodConstant.PING, "{}"));
        //FIXME 区分实时订单，预约单不用返回费用信息
        //pushCommon.sendDriverMsg(ctx, orderNo, vehicleId, oaDVehicleGps);
    }

    public void mileageBilling(ChannelHandlerContext ctx, String method, JSONObject jsonCon) {
        try {
            String key = jsonCon.getString(EMileageBilling.key.getValue());
            //根据订单取出数据的信息
            String orderNo = jsonCon.getString(EMileageBilling.orderNo.getValue());
            log.info("ORDER_HISTORY 订单号:[{}],上传key:[{}] 计费方法", orderNo, key);
            //总里程
            //
            BigDecimal currentMileage = new BigDecimal(jsonCon.getString(EMileageBilling.currentMileage.getValue()));
//            String orderRedisKey = RedisPrefixConstant.ORDER_OA_D_ORDER + orderNo;
//            if (redisCommon.hashKey(orderRedisKey)) {
//                OaCOrder order = JSON.parseObject(redisCommon.getStr(orderRedisKey), OaCOrder.class);
//                EOrderStatus byId = EOrderStatus.findById(order.getOrderStatus());
//                if (CheckUtil.objIsEmpty(order) || !EOrderStatus.isTrue(byId)) {
//                    return;
//                }
//                order.setIsFinalSett(0);
//                order = feignNettyService.getTimeFeeByIdOrder(order);
//                log.info("ORDER_HISTORY 订单号:[{}],上传key:[{}] 计费方法,当前时长: {}分钟, 当前时长费: {}元", orderNo, key, order.getDurationTime(), order.getDurationFee());
//                //-------------------------------时长费(end)------------------------------
//                //------------------------------里程费(start)------------------------------
//                order.setCurrentToatlMileage(currentMileage);
//                order = feignNettyService.getMileageFeeByOrder(order);
//                log.info("ORDER_HISTORY 订单号:[{}],上传key:[{}] 计费方法, 当前里程: [{}]公里 ,当前里程费: [{}]元", orderNo, key, order.getMilageDistance(), order.getMileageFee());
//                //------------------------------里程费(end)------------------------------
//                //------------------------------获取远途费(start)------------------------------
//                order = feignNettyService.getDistanceFeeByOrder(order);
//                log.info("ORDER_HISTORY 订单号:[{}],上传key:[{}] 计费方法, 当前远途距离: [{}]公里 ,当前远途费: [{}]元", orderNo, key, order.getEmptyDistance(), order.getDistanceFee());
//                //------------------------------获取远途费(end)------------------------------
//                //-------------------------------获取抽佣后的金额(start)------------------------------
//                BigDecimal durationFee = order.getDurationFee();
//                BigDecimal mileageFee = order.getMileageFee();
//                BigDecimal distanceFee = order.getDistanceFee();
//                BigDecimal startFee = order.getStartFee();
//                //获取基础计价费用的抽佣金额
//                BigDecimal totalBillFee = durationFee.add(mileageFee).add(distanceFee).add(startFee);
//                BigDecimal drawFee = feignNettyService.getDrawFee(totalBillFee, String.valueOf(order.getRulesId())).setScale(2, BigDecimal.ROUND_HALF_DOWN);
//                log.info("ORDER_HISTORY 订单号:[{}],上传key:[{}] 计费方法, 本次总金额为: [{}]元, 抽成后的金额为: [{}]元", orderNo, key, key, totalBillFee, drawFee);
//                //-------------------------------获取抽佣后的金额(start)-----------------------------
//                //设置总费用
//                order.setTotalFee(totalBillFee);
//                //设置司机显示的抽佣后的费用
//                order.setDrawFee(drawFee);
//                //设置订单信息
//                redisCommon.set(orderRedisKey, JSON.toJSONString(order));
//                log.info("ORDER_HISTORY 订单号:[{}],上传key:[{}] 计费方法,向滴滴同步计价-->开始", orderNo, key);
//                // 调用滴滴实时计价同步
//                RealtimeFeeSyncParam realtimeFeeSyncParam = new RealtimeFeeSyncParam();
//                realtimeFeeSyncParam.setOpen_oid(order.getDidiOrderId());
//                realtimeFeeSyncParam.setOrder_id(order.getOrderNo());
//                realtimeFeeSyncParam.setTotal_fee(totalBillFee);
////                iSyncDataService.realtimeFeeSync(realtimeFeeSyncParam);
//                producer.sendMsg(realtimeFeeSyncParam, MqConstant.REAL_TIME_FEE_SYNC);
//                log.info("ORDER_HISTORY 订单号:[{}],上传key:[{}] 计费方法,向滴滴同步计价-->结束,请求参数:[{}]", orderNo, key, realtimeFeeSyncParam);
//            }
        } catch (Exception e) {
            log.error("ORDER_HISTORY 计费方法异常,请求参数:[{}],异常信息:[{}]", jsonCon, e);
        }
    }


    /**
     * 司机获取用户信息
     *
     * @param ctx
     * @param method
     * @param jsonCon
     */
//    public void driverGetOrderMessage(ChannelHandlerContext ctx, String method, JSONObject jsonCon) {
//        String orderNo = jsonCon.getString("orderNo");
//        String key = jsonCon.getString("key");
//        //String driverToken = jsonCon.getString("driverToken");
//        pushCommon.sendDriverMsg(orderNo, ctx, key);
//    }
}
